"use strict";

const { Controller } = require("ee-core");
const Log = require("ee-core/log");
const Services = require("ee-core/services");
const parseTorrent = require("parse-torrent");
const { platform, arch } = process;
const fs = require("fs");

/**
 * example
 * @class
 */
class EngineController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  /**
   * 所有方法接收两个参数
   * @param args 前端传的参数
   * @param event - ipc通信时才有值。详情见：控制器文档
   */

  /**
   * test
   */
  async init() {
    const result = await Services.get("engine").start("electron");
    Log.info("service result:", result);

    return "hello electron-egg";
  }

  /**
   * 解析种子
   * @param {*} args
   * @returns
   */
  async parseTorrentC(args) {
    // Log.info('parseTorrentC', args);
    if (!args.path) {
      return false;
    }
    let res = parseTorrent(fs.readFileSync(args.path));
    // Log.info('parseTorrentC', res);
    return res;
  }

  /**
   * 获取任务列表
   * @param {*} args
   */
  async getTaskList(args) {
    const result = await Services.get("engineClient").fetchTaskList(args);
    return result;
  }

  async addTaskUri(args) {
    const res = await Services.get("engineClient").addUri(args);
    return res;
  }

  async addTorrent(args) {
    const res = await Services.get("engineClient").addTorrent(args);
    return res;
  }

  async addMetalink(args) {
    const res = await Services.get("engineClient").addMetalink(args);
    return res;
  }

  async stopAllTask(args) {
    const res = await Services.get("engineClient").pauseAllTask();
    return res;
  }

  async startAllTask(args) {
    const res = await Services.get("engineClient").resumeAllTask();
    return res;
  }

  /**
   *
   * @param {{
   * gid: []}} args
   * @returns
   */
  async removeTaskByGids(args) {
    const res = await Services.get("engineClient").batchRemoveTask(args);
    return res;
  }

  /**
   *
   * @param {{gid: String}} args
   * @returns
   */
  async stopByGid(args) {
    const res = await Services.get("engineClient").pauseTask(args);
    return res;
  }

  /**
   *
   * @param {{gid: String}} args
   * @returns
   */
  async startByGid(args) {
    try {
      const res = await Services.get("engineClient").resumeTask(args);
      return res;
    } catch (error) {
      return Promise.reject(error);
    }
  }
}

EngineController.toString = () => "[class EngineController]";
module.exports = EngineController;
